<template>
  <div class="app-container">
    <LineSelect ref="lineSelectRef" @select="handleLineSelect" />
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="车间名称" prop="workshopName">
        <el-input
          v-model="queryParams.workshopName"
          placeholder="请输入车间名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车间编号" prop="workshopCode">
        <el-input
          v-model="queryParams.workshopCode"
          placeholder="请输入车间编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车间类型" prop="workshopType">
        <el-select v-model="queryParams.workshopType" placeholder="请选择车间类型" clearable>
          <el-option
            v-for="dict in workshop_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="车间主管ID" prop="managerId">
        <el-input
          v-model="queryParams.managerId"
          placeholder="请输入车间主管ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="车间状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择车间状态" clearable>
          <el-option
            v-for="dict in workshop_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['bdm:workshop:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bdm:workshop:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bdm:workshop:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['bdm:workshop:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workshopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车间ID" align="center" prop="workshopId" />
      <el-table-column label="车间名称" align="center" prop="workshopName" />
      <el-table-column label="车间编号" align="center" prop="workshopCode" />
      <el-table-column label="车间类型" align="center" prop="workshopType">
        <template #default="scope">
          <dict-tag :options="workshop_type" :value="scope.row.workshopType"/>
        </template>
      </el-table-column>
      <el-table-column label="车间面积" align="center" prop="area" />
      <!-- <el-table-column label="车间主管ID" align="center" prop="managerId" /> -->
      <el-table-column label="车间状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="workshop_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bdm:workshop:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bdm:workshop:remove']">删除车间</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车间管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body >
      <el-form ref="workshopRef" :model="form" :rules="rules" label-width="80px" :inline="true">
        <el-form-item label="车间名称" prop="workshopName">
          <el-input v-model="form.workshopName" placeholder="请输入车间名称" />
        </el-form-item>
        <el-form-item label="车间编号" prop="workshopCode">
          <el-input v-model="form.workshopCode" placeholder="请输入车间编号" disabled/>
        </el-form-item>
        <el-form-item label="车间类型" prop="workshopType">
          <el-select v-model="form.workshopType" placeholder="请选择车间类型">
            <el-option
              v-for="dict in workshop_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车间面积" prop="area">
          <el-input v-model="form.area" placeholder="请输入车间面积" />
        </el-form-item>
        <!-- <el-form-item label="车间主管ID" prop="managerId">
          <el-input v-model="form.managerId" placeholder="请输入车间主管ID" />
        </el-form-item> -->
        <el-form-item label="车间状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择车间状态">
            <el-option
              v-for="dict in workshop_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">生产线管理信息</el-divider>
        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddProductionLine">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteProductionLine">删除</el-button>
          </el-col>
        </el-row> -->
        <el-table :data="productionLineList" :row-class-name="rowProductionLineIndex" @selection-change="handleProductionLineSelectionChange" ref="productionLine" >
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column label="序号" align="center" prop="index" width="200"/>
          <!-- <el-table-column label="生产线名称" prop="lineName" width="200">
            <template #default="scope">
              <el-input 
                v-model="scope.row.lineName" 
                placeholder="请选择生产线"
                readonly
                disabled
              >
                
                <template #append>
                  <el-button 
                    @click="handleSelectLine(scope.row)"
                   
                  >选择</el-button>
                </template>
              </el-input>
            </template>
          </el-table-column> -->
          
          <el-table-column label="生产线编号" prop="lineCode" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.lineCode" placeholder="请输入生产线编号" disabled />
            </template>
          </el-table-column>
          <el-table-column label="生产线状态" prop="lineStatus" width="200">
            <template #default="scope">
              <el-select v-model="scope.row.lineStatus" placeholder="请选择生产线状态" disabled>
                <el-option
                  v-for="dict in production_line_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="生产线类型" prop="lineType" width="200">
            <template #default="scope">
              <el-select v-model="scope.row.lineType" placeholder="请选择生产线类型" disabled>
                <el-option
                  v-for="dict in production_line_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="设计产能" prop="capacity" width="200">
            <template #default="scope">
              <el-input v-model="scope.row.capacity" placeholder="请输入设计产能" disabled/>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Workshop">
import { ref } from 'vue';
import LineSelect from "@/components/LineSelect";
import { listWorkshop, getWorkshop, delWorkshop, addWorkshop, updateWorkshop } from "@/api/bdm/workshop";
import { generateWorkshopCode } from "@/utils/generator";

const { proxy } = getCurrentInstance();
const { workshop_status, production_line_type, workshop_type, production_line_status } = proxy.useDict('workshop_status', 'production_line_type', 'workshop_type', 'production_line_status');

const workshopList = ref([]);
const productionLineList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedProductionLine = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workshopName: null,
    workshopCode: null,
    workshopType: null,
    // managerId: null,
    status: null,
  },
  rules: {
    workshopName: [
      { required: true, message: "车间名称不能为空", trigger: "blur" }
    ],
    workshopCode: [
      { required: true, message: "车间编号不能为空", trigger: "blur" }
    ],
    workshopType: [
      { required: true, message: "车间类型不能为空", trigger: "change" }
    ],
    area: [
      { required: true, message: "车间面积不能为空", trigger: "blur" }
    ],
    // managerId: [
    //   { required: true, message: "车间主管ID不能为空", trigger: "blur" }
    // ],
    status: [
      { required: true, message: "车间状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询车间管理列表 */
function getList() {
  loading.value = true;
  listWorkshop(queryParams.value).then(response => {
    workshopList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    workshopId: null,
    workshopName: null,
    workshopCode: null,
    workshopType: null,
    area: null,
    // managerId: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  productionLineList.value = [];
  proxy.resetForm("workshopRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.workshopId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 自动生成车间编号
  form.value.workshopCode = generateWorkshopCode();
  open.value = true;
  title.value = "添加车间管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _workshopId = row.workshopId || ids.value
  getWorkshop(_workshopId).then(response => {
    form.value = response.data;
    productionLineList.value = response.data.productionLineList;
    open.value = true;
    title.value = "修改车间管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["workshopRef"].validate(valid => {
    if (valid) {
      form.value.productionLineList = productionLineList.value;
      if (form.value.workshopId != null) {
        updateWorkshop(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWorkshop(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _workshopIds = row.workshopId || ids.value;
  proxy.$modal.confirm('是否确认删除车间管理编号为"' + _workshopIds + '"的数据项？').then(function() {
    return delWorkshop(_workshopIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 生产线管理序号 */
function rowProductionLineIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 生产线管理添加按钮操作 */
function handleAddProductionLine() {
  let obj = {};
  obj.lineName = "";
  obj.lineCode = "";
  obj.lineStatus = "";
  obj.lineType = "";
  obj.capacity = "";
  obj.remark = "";
  productionLineList.value.push(obj);
}

/** 生产线管理删除按钮操作 */
function handleDeleteProductionLine() {
  if (checkedProductionLine.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的生产线管理数据");
  } else {
    const productionLines = productionLineList.value;
    const checkedProductionLines = checkedProductionLine.value;
    productionLineList.value = productionLines.filter(function(item) {
      return checkedProductionLines.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleProductionLineSelectionChange(selection) {
  checkedProductionLine.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('bdm/workshop/export', {
    ...queryParams.value
  }, `workshop_${new Date().getTime()}.xlsx`)
}
const lineSelectRef = ref();

function handleLineSelect(line) {
  // 这里处理从LineSelect组件返回的生产线数据
  // 可以根据实际需求进行处理
  console.log('Selected line:', line);
}

function handleSelectLine(row) {
  if (!lineSelectRef.value) return;

  // 使用闭包保存当前行的引用
  const handleSelection = (selectedLine) => {
    if (selectedLine) {
      row.lineName = selectedLine.lineName;
      row.lineCode = selectedLine.lineCode;
      row.lineStatus = selectedLine.lineStatus;
      row.lineType = selectedLine.lineType;
      row.capacity = selectedLine.capacity;
      proxy.$modal.msgSuccess("生产线选择成功");
    }
  };

  // 每次调用都重新注册监听，确保能正确更新对应的行
  lineSelectRef.value.onSelect(handleSelection);
  
  // 显示选择对话框
  lineSelectRef.value.show();
}
getList();
</script>
